package main.gui;

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.JSeparator;

import org.apache.log4j.Logger;
import org.xml.sax.SAXException;

import main.java.DAO;
import main.java.GSI2LandXML;
import main.java.Hsqldb;
import model.entities.UserCode;

import java.awt.Color;

public class MainGui extends JFrame implements ActionListener {

	private static final long serialVersionUID = 1L;

	private static Logger logger = Logger.getLogger(MainGui.class);

	private JPanel contentPane;
	private JTextField textField;
	private JTextField textField_1;
	private JTextField textField_2;
	private JButton save;
	private JButton chooseFiles;
	private JButton convert;
	private JButton close;
	private JButton clear;
	private JTextPane textPane;

	private File[] gsiFiles;
	private JTextField textField_3;
	private JLabel lblNewLabel;
	private JLabel lblOnlyCgpRo;
	private JLabel lblCgpro;
	private JLabel wrongfile;
	private JLabel gsiConvert;

	private GSI2LandXML converter = null;
	private String result = "";

	private static Hsqldb hsqlServer = null;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					hsqlServer = new Hsqldb();
					hsqlServer.startHsqlDB();
					MainGui frame = new MainGui();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public MainGui() {
		setTitle("Data set migration group 2");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 600, 400);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);

		JLabel lblUserInputs = new JLabel("User Inputs:");
		lblUserInputs.setBounds(249, 6, 92, 16);
		contentPane.add(lblUserInputs);

		textField = new JTextField();
		textField.setForeground(Color.BLACK);
		textField.setBounds(80, 28, 140, 28);
		textField.setColumns(10);
		contentPane.add(textField);

		JLabel lblUserCode = new JLabel("User Code:");
		lblUserCode.setBounds(6, 34, 92, 16);
		contentPane.add(lblUserCode);

		JLabel lblWi = new JLabel("WI:");
		lblWi.setBounds(232, 34, 30, 16);
		contentPane.add(lblWi);

		textField_1 = new JTextField();
		textField_1.setBounds(284, 28, 140, 28);
		textField_1.setColumns(10);
		contentPane.add(textField_1);

		JLabel lblLabel = new JLabel("Label:");
		lblLabel.setBounds(6, 62, 61, 16);
		contentPane.add(lblLabel);

		textField_2 = new JTextField();
		textField_2.setBounds(80, 56, 140, 28);
		textField_2.setColumns(10);
		contentPane.add(textField_2);

		save = new JButton("Save");
		save.setBounds(450, 138, 117, 29);
		save.addActionListener(this);
		save.setActionCommand("save");
		contentPane.add(save);

		JLabel lblConvertion = new JLabel("Conversion:");
		lblConvertion.setBounds(249, 189, 92, 16);
		contentPane.add(lblConvertion);

		chooseFiles = new JButton("Choose Files");
		chooseFiles.setBounds(327, 330, 117, 29);
		chooseFiles.addActionListener(this);
		chooseFiles.setActionCommand("choose");
		contentPane.add(chooseFiles);

		convert = new JButton("Convert");
		convert.setBounds(450, 330, 117, 29);
		convert.addActionListener(this);
		convert.setActionCommand("convert");
		contentPane.add(convert);

		JLabel lblChosenFiles = new JLabel("Chosen Files:");
		lblChosenFiles.setBounds(6, 257, 92, 16);
		contentPane.add(lblChosenFiles);

		textPane = new JTextPane();
		textPane.setEditable(false);
		textPane.setBounds(99, 217, 468, 101);
		contentPane.add(textPane);

		JSeparator separator = new JSeparator();
		separator.setBounds(6, 166, 588, 12);
		contentPane.add(separator);

		close = new JButton("Close");
		close.setBounds(6, 330, 117, 29);
		close.addActionListener(this);
		close.setActionCommand("close");
		contentPane.add(close);

		JLabel lblTarget = new JLabel("Target:");
		lblTarget.setBounds(232, 62, 61, 16);
		contentPane.add(lblTarget);

		textField_3 = new JTextField();
		textField_3.setBounds(284, 56, 140, 28);
		textField_3.setColumns(10);
		contentPane.add(textField_3);

		clear = new JButton("Clear");
		clear.setBounds(6, 138, 117, 29);
		clear.addActionListener(this);
		clear.setActionCommand("clear");
		contentPane.add(clear);

		lblNewLabel = new JLabel("UserCode added!");
		lblNewLabel.setBounds(224, 138, 117, 16);
		lblNewLabel.setVisible(false);
		lblNewLabel.setForeground(Color.green);
		contentPane.add(lblNewLabel);

		lblOnlyCgpRo = new JLabel("Inputs only: CGP, RO,");
		lblOnlyCgpRo.setBounds(428, 62, 202, 16);
		contentPane.add(lblOnlyCgpRo);

		lblCgpro = new JLabel("CGP-RO");
		lblCgpro.setBounds(507, 79, 61, 16);
		contentPane.add(lblCgpro);

		wrongfile = new JLabel("Wrong File Format!");
		wrongfile.setForeground(Color.RED);
		wrongfile.setBounds(164, 335, 139, 16);
		wrongfile.setVisible(false);
		contentPane.add(wrongfile);

		gsiConvert = new JLabel("LandXml File generated!");
		gsiConvert.setForeground(Color.GREEN);
		gsiConvert.setBounds(152, 335, 163, 16);
		gsiConvert.setVisible(false);
		contentPane.add(gsiConvert);
	}

	public void actionPerformed(ActionEvent e) {
		if(e.getActionCommand().equals("choose")) {
			wrongfile.setVisible(false);
			gsiConvert.setVisible(false);
			textPane.setForeground(Color.black);
			JFileChooser fc = new JFileChooser();
			fc.setMultiSelectionEnabled(true);
			fc.showOpenDialog(rootPane);
			gsiFiles = fc.getSelectedFiles();
			String out = "";
			for (int i = 0; i < gsiFiles.length; i++) {
				out += gsiFiles[i].getAbsolutePath() + "\n";
			}
			textPane.setText(out);
		}

		if(e.getActionCommand().equals("convert")) {
			ArrayList<String> files = new ArrayList<String>();
			boolean ok = true;
			for (int i = 0; i < gsiFiles.length; i++) {
				if (gsiFiles[i].getAbsolutePath().substring(gsiFiles[i].getAbsolutePath().length() - 4).equals(".gsi")) {
					files.add(gsiFiles[i].getAbsolutePath());
				} else {
					ok = false;
					textPane.setForeground(Color.red);
					wrongfile.setVisible(true);
				}
			}
			if (ok) {
				try {
					convertDocuments(files);
					if (result.equals("GSI CONVERSION FAILED. GSI content is not valid.")) {
						JOptionPane.showMessageDialog(new JFrame(), "GSI File content is not valid!", "GSI File Failed!", JOptionPane.ERROR_MESSAGE);
					} else {
						File xmlFile = new File(converter.getXmlOutputPath());
						if (!converter.validateLandXML(xmlFile)) {
							JOptionPane.showMessageDialog(new JFrame(), "Generated LandXML File content is not valid!", "LandXML File Failed!", JOptionPane.ERROR_MESSAGE);	
						} else {
							gsiConvert.setVisible(true);
							JOptionPane.showMessageDialog(new JFrame(), "Convert GSI to LandXML successful!\n\nTotal Number of Datawords:"+ converter.getTotalNumberOfDatawords() + "\nNumber of success interpretated datawords: " 
									+ converter.getSuccessCounter() + "\nNumber of failed interpretated datawords: " + converter.getFailedCounter(), "Conversion", JOptionPane.INFORMATION_MESSAGE);	
						}
					}
				} catch (IOException e1) {
					JOptionPane.showMessageDialog(new JFrame(), "Input Output Exception!", "IOException", JOptionPane.ERROR_MESSAGE);
				} catch (SAXException sax) {
					JOptionPane.showMessageDialog(new JFrame(), "SAX Exception!", "SAXException", JOptionPane.ERROR_MESSAGE);
				}
			}
		}

		if(e.getActionCommand().equals("save")) {
			boolean ok = true;
			UserCode uc = new UserCode();
			if (textField.getText().matches("[0-9]+")) {
				uc.setCode(Integer.parseInt(textField.getText()));
			} else {
				ok = false;
				textField.setForeground(Color.red);
			}
			if (textField_1.getText().matches("[0-9]+")) {
				uc.setWi(Integer.parseInt(textField_1.getText()));
			} else {
				ok = false;
				textField_1.setForeground(Color.red);
			}
			uc.setLabel(textField_2.getText());
			if (textField_3.getText().matches("CGP") || textField_3.getText().matches("RO") || textField_3.getText().matches("CGP-RO")) {
				uc.setTarget(textField_3.getText());
			} else {
				ok = false;
				textField_3.setForeground(Color.red);
			}

			if (ok) {
				DAO dao = new DAO();
				dao.addUserCode(uc);
				lblNewLabel.setVisible(true);
			}

		}

		if (e.getActionCommand().equals("close")) {
			hsqlServer.closeHsqlDB();
			System.exit(0);
		}

		if (e.getActionCommand().equals("clear")) {
			textField.setText("");
			textField.setForeground(Color.black);
			textField_1.setText("");
			textField_1.setForeground(Color.black);
			textField_2.setText("");
			textField_3.setText("");
			textField_3.setForeground(Color.black);
			lblNewLabel.setVisible(false);
		}
	}

	public void convertDocuments(ArrayList<String> files) throws IOException
	{
		logger.debug("Starting conversion...");
		converter = new GSI2LandXML();
		result = converter.convertGSI2LandXML(files);
		logger.debug("Conversion finished");
	}
}
